package com.adapters.db;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.adapters.GroupMemberAdapter;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;

public class ContentProviderDB extends ContentProvider {
	/*
	 * static fields
	 */
	public static final String AUTHORITY = "com.senditcertified.mail.database";
	public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY);
	public static final String PREFIX = "sendit_certified_";
	public static final String KEY_TRUE = "true";
	public static final String KEY_FALSE = "false";

	public static final String COL_ID = PREFIX + "id";
	public static final String COL_TITLE = PREFIX + "title";
	public static final String COL_CODE = PREFIX + "code";
	public static final String COL_CONTACT_ID = PREFIX + "contact_id";
	public static final String COL_EMAIL = PREFIX + "email";
	public static final String COL_ORDER = PREFIX + "order";
	public static final String COL_FIRST_NAME = PREFIX + "first_name";
	public static final String COL_LAST_NAME = PREFIX + "last_name";
	public static final String COL_GROUP_ID = PREFIX + "group_id";
	public static final String COL_DATE = PREFIX + "date";
	public static final String COL_DESCRIPTION = PREFIX + "description";
	public static final String COL_STATUS = PREFIX + "status";

	private DatabaseHelper mDbHelper;

	private class DatabaseHelper extends SQLiteOpenHelper {
		private static final String DATABASE_NAME = "SenditCertifiedDB";
		private static final int DATABASE_VERSION = 4;
		private String DB_PATH;
		private SQLiteDatabase dataBase;

		public DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
			DB_PATH = "/data/data/"
					+ getContext().getApplicationContext().getPackageName()
					+ "/databases/";
		}

		@Override
		public void onCreate(SQLiteDatabase database) {
			// TODO
			database.execSQL(CountrySMSCodeTableAdapter.CREATE_TABLE);
			database.execSQL(ContactTableAdapter.CREATE_TABLE);
			database.execSQL(GroupTableAdapter.CREATE_TABLE);
			database.execSQL(GroupMemberTableAdapter.CREATE_TABLE);
			database.execSQL(SecurePackageLogTableAdapter.CREATE_TABLE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase database, int oldVersion,
				int newVersion) {
			database.execSQL("DROP TABLE IF EXISTS "
					+ CountrySMSCodeTableAdapter.TABLE_NAME);
			database.execSQL("DROP TABLE IF EXISTS "
					+ ContactTableAdapter.TABLE_NAME);
			database.execSQL("DROP TABLE IF EXISTS "
					+ GroupTableAdapter.TABLE_NAME);
			database.execSQL("DROP TABLE IF EXISTS "
					+ GroupMemberTableAdapter.TABLE_NAME);
			database.execSQL("DROP TABLE IF EXISTS "
					+ SecurePackageLogTableAdapter.TABLE_NAME);
			onCreate(database);
		}

		@Override
		public synchronized void close() {
			if (dataBase != null)
				dataBase.close();
			super.close();
		}

		public boolean createDataBase() {
			boolean dbExist = checkDataBase();
			if (!dbExist) {
				this.getReadableDatabase();
				try {
					copyDataBase();
				} catch (IOException e) {
					e.printStackTrace();
					return false;
				}
			}
			return true;
		}

		private boolean checkDataBase() {
			SQLiteDatabase checkDB = null;
			try {
				String myPath = DB_PATH + DATABASE_NAME;
				checkDB = SQLiteDatabase.openDatabase(myPath, null,
						SQLiteDatabase.OPEN_READONLY);

			} catch (SQLiteException e) {
				if (checkDB != null) {
					checkDB.close();
				}
			}
			if (checkDB != null) {
				checkDB.close();
			}
			return checkDB != null ? true : false;
		}

		private void copyDataBase() throws IOException {
			InputStream myInput = getContext().getAssets().open(DATABASE_NAME);
			String outFileName = DB_PATH + DATABASE_NAME;
			OutputStream myOutput = new FileOutputStream(outFileName);
			byte[] buffer = new byte[1024];
			int length;
			while ((length = myInput.read(buffer)) > 0) {
				myOutput.write(buffer, 0, length);
			}
			myOutput.flush();
			myOutput.close();
			myInput.close();
		}

	}

	// content Provider Override
	@Override
	public int delete(Uri uri, String where, String[] selectionArgs) {
		String table = getTableName(uri);
		SQLiteDatabase dataBase = mDbHelper.getWritableDatabase();
		return dataBase.delete(table, where, selectionArgs);
	}

	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		SQLiteDatabase mDB = mDbHelper.getWritableDatabase();
		long rowID = mDB.insert(getTableName(uri), null, values);
		if (rowID > 0) {
			Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
			getContext().getContentResolver().notifyChange(_uri, null);
			return _uri;
		}
		throw new SQLException("Failed to add a record into " + uri);
	}

	@Override
	public boolean onCreate() {
		mDbHelper = new DatabaseHelper(getContext());
		if (mDbHelper != null) {
			mDbHelper.createDataBase();
			return false;
		} else
			return true;

	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		// Log.e("aaaaaaaaaa",uri.toString());
		String table = getTableName(uri);
		SQLiteDatabase database = mDbHelper.getReadableDatabase();
		Cursor cursor = database.query(table, projection, selection,
				selectionArgs, null, null, sortOrder);
		return cursor;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		String table = getTableName(uri);
		SQLiteDatabase database = mDbHelper.getWritableDatabase();
		return database.update(table, values, selection, selectionArgs);
	}

	public String getTableName(Uri uri) {
		String value = uri.getLastPathSegment();
		// Log.e("----------TABLE--------------",value);
		return value;
	}

	public static void clearAllData(Context mContext) {
		new ContactTableAdapter(mContext).clear();
		new GroupTableAdapter(mContext).clear();
		new GroupMemberTableAdapter(mContext).clear();
		new SecurePackageLogTableAdapter(mContext).clear();
	}

}